package com.iflytek.cosmo.ocr.support.license.server;

import java.time.Clock;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.regex.Pattern;

import cn.hutool.core.util.StrUtil;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author <a href=mailto:ktyi@iflytek.com>伊开堂</a>
 * @date 2021/6/29
 */
@Data
public class ServerLicense {
    protected final Logger logger = LoggerFactory.getLogger(getClass());

    /** 字段分隔符 */
    protected static final String FIELD_SEPARATOR = ".";

    /** 子版本类使用的格式分隔符 */
    protected static final String SUBCLASS_SEPARATOR = "#";

    protected static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMddHHmm").withZone(
            ZoneId.systemDefault());
    protected static final Pattern FIELD_SPLITTOR = Pattern.compile("\\" + FIELD_SEPARATOR);

    /** 序列号版本, 不超过100 */
    protected int version;

    /** 序列号生成时间 */
    protected Instant createTime;

    public ServerLicense() {
    }

    public ServerLicense(String license) {
        String baseInfo = license.substring(0, license.indexOf(SUBCLASS_SEPARATOR));
        String[] infos = FIELD_SPLITTOR.split(baseInfo);
        String versionStr = infos[0];
        String createTimeStr = infos[1];
        this.version = Integer.parseInt(versionStr.substring(versionStr.length() - 2));
        this.createTime = DATE_TIME_FORMATTER.parse(createTimeStr, Instant::from);
    }

    public boolean valid() {
        if (this.version <= 0) {
            logger.info("授权异常, version小于0");
            return false;
        }
        Instant now = Instant.now(Clock.systemDefaultZone());
        if (now.compareTo(createTime) <= 0) {
            logger.info("授权异常, 请检查服务器时间设置. 当前服务器时间: {}", DATE_TIME_FORMATTER.format(now));
            return false;
        }
        return true;
    }


    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        // 版本号
        sb.append(StrUtil.padPre(String.valueOf(version), 2, "0")).append(FIELD_SEPARATOR);
        // 创建时间
        sb.append(DATE_TIME_FORMATTER.format(createTime));

        sb.append(SUBCLASS_SEPARATOR);
        return sb.toString();
    }

}
